#!/usr/bin/env python3
"""
初始化视频元数据
为已存在的视频文件创建元数据记录
"""

import os
import json
from pathlib import Path
from datetime import datetime

def init_video_metadata():
    """初始化视频元数据"""
    upload_dir = Path("uploads")
    metadata_file = upload_dir / "video_metadata.json"
    
    # 确保上传目录存在
    upload_dir.mkdir(exist_ok=True)
    
    # 获取现有视频文件
    video_files = []
    for ext in ['*.mp4', '*.avi', '*.mov', '*.mkv']:
        video_files.extend(upload_dir.glob(ext))
    
    print(f"发现 {len(video_files)} 个视频文件")
    
    # 加载现有元数据
    metadata = {}
    if metadata_file.exists():
        try:
            with open(metadata_file, 'r', encoding='utf-8') as f:
                metadata = json.load(f)
            print(f"加载了现有元数据，包含 {len(metadata)} 条记录")
        except Exception as e:
            print(f"加载元数据失败: {e}")
    
    # 为每个视频文件创建元数据记录
    added_count = 0
    for video_file in video_files:
        filename = video_file.name
        
        # 如果已存在记录，跳过
        if filename in metadata:
            print(f"跳过已存在的记录: {filename}")
            continue
        
        # 获取文件信息
        file_size = video_file.stat().st_size
        
        # 创建元数据记录
        metadata[filename] = {
            "original_name": filename,  # 由于是现有文件，使用文件名作为原始名称
            "file_size": file_size,
            "upload_time": datetime.now().isoformat(),
            "video_url": f"http://192.168.210.72:8000/videos/{filename}"
        }
        
        added_count += 1
        print(f"添加记录: {filename} ({file_size / (1024*1024):.2f} MB)")
    
    # 保存元数据
    try:
        with open(metadata_file, 'w', encoding='utf-8') as f:
            json.dump(metadata, f, ensure_ascii=False, indent=2)
        print(f"元数据已保存到: {metadata_file}")
        print(f"新增 {added_count} 条记录，总计 {len(metadata)} 条记录")
    except Exception as e:
        print(f"保存元数据失败: {e}")

if __name__ == "__main__":
    init_video_metadata()